package com.taomeng.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uri = req.getRequestURI();
        String[] paths = uri.split("/");
        String methodName = paths[paths.length - 1];
        System.out.println(uri+"-----"+methodName);
        //通过方法名获取到方法的对象
        //获取当前类的Class对象
        Class cla = this.getClass();
        //获取cla的方法（Method对象）
        //getDeclaredMethod需要两个参数，方法名和参数名
        //因为在java需要通过方法名和参数列表来确定一个方法
        try {
            //获取方法对象
            Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //设置方法的访问权限
            method.setAccessible(true);     //该方法可以取消Java的权限控制检查，就可以调用类的私有属性和方法
            //调用方法
            //invoke用于调用一个方法，第一个参数时要调用方法的对象，剩下是调用方法需要的参数
            method.invoke(this, req, resp);         //方法调用，传递调用对象及参数
        } catch (Exception e) {
            req.setAttribute("exception", e.getClass().getName());
            if (e instanceof NoSuchMethodException) {
                req.getRequestDispatcher("/error/404.jsp").forward(req, resp);
            } else {
                req.getRequestDispatcher("/error/unknowEror.jsp").forward(req,resp);
            }
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        doGet(req, resp);
    }
}
